#!/usr/bin/make -f

ELECTRON_VERSION = `curl -s 'https://archlinux.org/packages/community/x86_64/electron/json/' | python3 -c "import sys, json; print(json.load(sys.stdin)['pkgver'])"`

ifeq (##ARCH, amd64)
	_arch = x64
endif
ifeq (##ARCH, i386)
	_arch = ia32
endif
ifeq (##ARCH, arm64)
	_arch = arm64
endif
ifeq (##ARCH, armhf)
	_arch = arm
endif

%:
	dh ${@}


override_dh_auto_build:
	# Remove Electron bundle
	sed -i '/"electron":/d' package.json
	sed -i '/"electron-builder":/d' package.json
	sed -i '/"electron-rebuild":/d' package.json
	sed -i '/"electron-devtools-installer":/d' package.json

	# Do not rebuild node modules
	sed -i '/"postinstall":/d' package.json
	
	# Use system ripgrep
	sed -i '/"vscode-ripgrep":/d' package.json
	
	# Reduce output of webpack
	sed -i 's|webpack |webpack --stats minimal |g' package.json
	sed -i 's| --progress||g' package.json

	# Set Electron version in babel.config.js
	sed -i "s|require('electron/package.json').version|'$(ELECTRON_VERSION)'|g" babel.config.js

	# Disable no-unresolved check
	sed -i "s|'no-console': 'off'|'no-console': 'off', 'import/no-unresolved': 'off'|g" .eslintrc.js
	
	# Set Electron version for building native modules
	echo "disturl \"https://atom.io/download/electron\"" > .yarnrc
	echo "target \"$(ELECTRON_VERSION)\"" >> .yarnrc
	echo "runtime \"electron\"" >> .yarnrc
	
	# Build
	yarn install --arch=$(_arch)
	yarn run pack
	yarn install --arch=$(_arch) --production --ignore-scripts --prefer-offline
	
	# Delete unused files according to electron-builder.yml
	rm -f node_modules/**/{CHANGELOG.md,README.md,README,readme.md,readme}
	rm -rf node_modules/dagre-d3-renderer/dist/demo
	rm -rf node_modules/dragula/resources
	rm -f node_modules/**/*.js.map
	rm -f node_modules/**/*.ts.map
	rm -rf node_modules/@felixrieseberg/spellchecker/bin
	rm -rf node_modules/@hfelix/spellchecker/bin
	rm -rf node_modules/ced/bin
	rm -rf node_modules/ced/vendor
	rm -rf node_modules/cld/bin
	rm -rf node_modules/cld/deps
	rm -rf node_modules/fontmanager-redux/bin
	rm -rf node_modules/keyboard-layout/bin
	rm -rf node_modules/keytar/bin
	rm -rf node_modules/vscode-windows-registry/bin
	rm -rf node_modules/@felixrieseberg/spellchecker/vendor
	rm -rf node_modules/@hfelix/spellchecker/vendor
	rm -f node_modules/@hfelix/spellchecker/build/Release/hunspell.a
	rm -f node_modules/ced/build/Release/compact_enc_det.a
	
	# Delete build files
	rm -rf node_modules/**/build/Release/obj.target
	rm -rf node_modules/@hfelix/spellchecker/build/Release/obj.target
	rm -rf node_modules/.cache

